package model

import (
	"fmt"
	"time"
)

// Article 文章模型
type Article struct {
	ID         uint      `gorm:"primary_key;not null;auto_increment" json:"id"`
	Title      string    `json:"title" gorm:"type:varchar(128)" binding:"required"`
	Time       time.Time `json:"time"`
	Content    string    `json:"content" binding:"required"`
	CategoryID uint      `json:"category_id"`

	Tags     []Tag    `gorm:"many2many:article_tags" json:"tags"`
	Category Category `json:"category"`
}

// GetCategoryArticle 获取一个栏目下的文章
func GetCategoryArticle(id, page, size int) (articles []Article, totalCount int64, err error) {
	if id != 0 {
		DB.Where("category_id=?", id).Model(&Article{}).Count(&totalCount)
		err = DB.Where("category_id=?", id).Select("id,title,category_id").Preload("Category").Preload("Tags").Order("id desc").Offset((page - 1) * size).Limit(size).Find(&articles).Error
	} else {
		err = DB.Select("id,title,time,category_id").Preload("Category").Preload("Tags").Order("id desc").Offset((page - 1) * size).Limit(size).Find(&articles).Error
		DB.Model(&Article{}).Count(&totalCount)
	}

	return
}

// FindArticle 获取文章详情
func FindArticle(id int) (article Article, err error) {
	err = DB.Preload("Category").Preload("Tags").Where("id=?", id).First(&article).Error

	return
}

// AddArticle 添加文章
func (article *Article) AddArticle() (err error) {
	article.Time = time.Now()
	err = DB.Create(&article).Error
	return
}

func SearchArticle(txt string) (result []Article) {
	DB.Where("title like ? or content like ?", fmt.Sprintf("%%%s%%", txt), fmt.Sprintf("%%%s%%", txt)).Find(&result)
	return
}

// DeleteArticle 删除文章
func DeleteArticle(id int) (err error) {
	err = DB.Delete(&Article{}, id).Error
	if err == nil {
		DB.Exec("delete from article_tags where article_id=?", id)
	}
	return
}

func (inst *Article) Update() (err error) {
	err = DB.Save(inst).Error
	return
}

func UpdateArticleCategory(id, cid uint) (err error) {
	err = DB.Model(&Article{}).Where("id=?", id).Update("category_id", cid).Error
	return
}
